package com.atguigu.gmall.realtime.util;

import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;

import java.io.IOException;
import java.io.StringReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.TimeZone;

/**
 * @Author lzc
 * @Date 2022/4/14 15:11
 */
public class AtguiguUtil {
    public static <T> List<T> toList(Iterable<T> elements) {
        ArrayList<T> result = new ArrayList<>();
        for (T element : elements) {
            result.add(element);
            
        }
        return result;
    }
    
    public static Long toTs(String dateTime, String... format) {
        String f = "yyyy-MM-dd HH:mm:ss";
        if (format.length == 1) {
            f = format[0];
        }
        try {
            return new SimpleDateFormat(f).parse(dateTime).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static String toDateTime(long ts, String... format) {
        String f = "yyyy-MM-dd HH:mm:ss";
        if (format.length == 1) {
            f = format[0];
        }
        SimpleDateFormat sdf = new SimpleDateFormat(f);
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        return sdf.format(ts);
    }
    
    public static void main(String[] args) throws IOException {
        List<String> list = splitByIk("手机 华为手机  5g手机");
        for (String w : list) {
            System.out.println(w);
        }
    }
    
    public static List<String> splitByIk(String kw) throws IOException {
        ArrayList<String> words = new ArrayList<>();
        // string  -> Reader
        // 内存流
        StringReader reader = new StringReader(kw);
        IKSegmenter ikSegmenter = new IKSegmenter(reader, true);
        
        Lexeme next = ikSegmenter.next();
        while (next != null) {
            String word = next.getLexemeText();
            words.add(word);
            next = ikSegmenter.next();
        }
        
        
        HashSet<String> set = new HashSet<>(words);
        words.clear();
        words.addAll(set);
    
        return words;
    }
}
